/********************************************************************************
 * Project Name		[JavaEE_Web]
 * File Name     	[HtmlConvertorTag.java]
 * Creation Date 	[2015-01-01]
 * 
 * Copyright© ge.y.yang@gmail.com All Rights Reserved
 * 
 * Work hard, play harder, think big and keep fit
 ********************************************************************************/
package jsp.tag.cases;

import java.io.IOException;
import java.io.StringWriter;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;

/**
 * Html转移Tag
 * 
 * @author 不落的太阳(Sean Yang aka ShortPeace)
 * @version 1.0
 * @since jdk 1.8
 * 
 */
public class HtmlConvertorTag extends SimpleTagSupport {

	/**
	 * 转义方法
	 * 
	 * @param html
	 * @return
	 */
	private String convertor(String html) {
		if (html == null) {
			return null;
		}
		// 使用字符数组保存html的每一个字符
		char[] contents = new char[html.length()];
		html.getChars(0, html.length(), contents, 0);
		StringBuilder builder = new StringBuilder();
		for (char ch : contents) {
			switch (ch) {
			case '<':
				builder.append("&lt;");
				break;
			case '>':
				builder.append("&gt;");
				break;
			case '&':
				builder.append("&amp;");
				break;
			case '"':
				builder.append("&quot;");
				break;
			default:
				builder.append(ch);
			}
		}
		return builder.toString();
	}

	@Override
	public void doTag() throws JspException, IOException {
		// 先将标签体内容输出到StringWriter
		StringWriter out = new StringWriter();
		this.getJspBody().invoke(out);

		String html = out.getBuffer().toString();
		html = this.convertor(html);
		this.getJspContext().getOut().write(html);
	}
}
